package com.dhy.utils;

import org.springframework.util.Assert;

import java.text.SimpleDateFormat;
import java.time.DayOfWeek;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

public class DateUtils
{
    /**
     * 计算每个月的天数
     *
     * @param year 年份
     * @param month 月份
     * @return days 每个月的天数
     */
    public static int getDaysOfMonth(int year, int month)
    {
        int days = 0;

        if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12)
        {
            days = 31;
        }
        else if (month == 4 || month == 6 || month == 9 || month == 11)
        {
            days = 30;
        }
        else
        { // 2月份，闰年29天、平年28天
            if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
            {
                days = 29;
            }
            else
            {
                days = 28;
            }
        }

        return days;
    }

    //格式化日期
    private static int[] dateFormatter(Date date)
    {
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        String format = simpleDateFormat.format(date);
        String[] formatter = format.split("-");
        //指定年
        int year=Integer.parseInt(formatter[0]);
        //指定月
        int month = Integer.parseInt(formatter[1]);
        //指定天
        int monthOfDay = Integer.parseInt(formatter[2]);
        Assert.isTrue((month>=9&&month<=12)||month==1,"月份不在指定范围内");
        if(month==9)
        {
            if(monthOfDay<6)
            {
                throw new IllegalArgumentException("九月份的从第六天开始查询");
            }
        }
        else if(month==1)
        {
            if(monthOfDay>23)
            {
                throw new IllegalArgumentException("一月份的第二十三天结束查询");
            }
        }
         int[] res=new int[2];
        res[0]=month;
        res[1]=monthOfDay;
        return res;
    }

    //计算当前月份，当前天是属于上课的第几周
   public static int calculateTermWeek(Date date)
   {
       int[] formatter = dateFormatter(date);
       int month=formatter[0];
       int monthOfDay=formatter[1];
       //计算month和9月份之间差了多少天
       if(month==1)
       {
       return (24+31+30+31+monthOfDay)/7+1;
       }
       int sum=-6;
       int start=9;
       int year = LocalDateTime.now().getYear();
       for(int i=0;i<(month-9);i++)
       {
           sum+=getDaysOfMonth(year,start++);
       }
       return sum/7+1;
   }

    public static int calculateTermWeekDay(Date date)
    {
        LocalDateTime dateTime=LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
        DayOfWeek dayOfWeek = dateTime.getDayOfWeek();
        return dayOfWeek.getValue();
    }


}
